﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;

namespace BlogsManage
{
    public partial class frmMain : Form
    {
        DBhelp db = new DBhelp();
        //创建数据集
        DataSet ds = new DataSet();
        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.dgvArticles.AutoGenerateColumns = false;
            BindDGV();
        }

        public void BindDGV()
        {
            if (ds.Tables["Articles"] != null)
            {
                ds.Tables["Articles"].Clear();
            }

            string sql = "SELECT * FROM Articles";
            SqlDataAdapter dataAdapter = db.GetData(sql);

            dataAdapter.Fill(ds, "Articles");
            this.dgvArticles.DataSource = ds.Tables["Articles"];


        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            frmAdd fa = new frmAdd();
            fa.fm = this;
            fa.Show();
        }

        private void tsmiUpdate_Click(object sender, EventArgs e)
        {
            if (this.dgvArticles.SelectedRows.Count == 1)
            {
                frmUpdate fu = new frmUpdate();
                fu.fm = this;
                fu.txtId.Text = this.dgvArticles.SelectedRows[0].Cells["Id"].Value.ToString();
                fu.txtti_name.Text = this.dgvArticles.SelectedRows[0].Cells["Title"].Value.ToString();
                fu.txtti_gender.Text = this.dgvArticles.SelectedRows[0].Cells["Author"].Value.ToString();
                fu.txtti_unitname.Text = this.dgvArticles.SelectedRows[0].Cells["Info"].Value.ToString();
                fu.Show();
            }
            else
            {
                MessageBox.Show("请选择要修改的文章");
            }
            
        }

        private void tsmiDelete_Click(object sender, EventArgs e)
        {
            if (this.dgvArticles.SelectedRows.Count == 1)
            {
                 DialogResult dia= MessageBox.Show("确认要删除么?", "操作", MessageBoxButtons.OKCancel);
                if (dia== DialogResult.OK)
                {
                    int id = int .Parse(this.dgvArticles.SelectedRows[0].Cells["Id"].Value.ToString());
                    string sql = "Delete from Articles where Id = "+id;
                    int result = db.IDU(sql);
                    if (result == 1)
                    {
                        MessageBox.Show("删除成功！");
                        this.BindDGV();
                    }
                    else
                    {
                        MessageBox.Show("删除失败！");
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择要修改的文章");
            }
        }
    }
}
